package org.chen.boot;

import org.chen.mvc.factory.ControllerFactory;
import org.chen.mybatis.factory.MapperProxyFactory;
import org.chen.spring.core.factory.BeanFactory;
import org.chen.spring.core.io.ResourceLoaderFactory;
import org.chen.boot.web.WebServer;
import org.chen.spring.ChenApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;

/**
 * 启动入口
 *
 * @author Chen
 * @since 2023/6/7 12:11
 */

public class ChenApplication {

    public static ChenApplicationContext run(Class<?> clazz, String... args) {
        Logger logger = LoggerFactory.getLogger(clazz);
        // 加载配置文件
        ResourceLoaderFactory.loaderResource(Arrays.asList(clazz.getPackageName(), ChenApplication.class.getPackageName(), "org.chen.mybatis"));

        printBanner(logger);

        //初始化MapperProxyFactory
        MapperProxyFactory.init(clazz);

        //初始化ControllerBean
        ControllerFactory.init();

        //初始化Spring容器
        ChenApplicationContext chenApplicationContext = new ChenApplicationContext(clazz);

        //获取Bean工厂
        BeanFactory beanFactory = ChenApplicationContext.getBeanFactory();

        //初始化WebServer
        Map<String, WebServer> webServerMap = beanFactory.getBeansOfType(WebServer.class);
        
        //启动WebServer
        new Thread(() -> {
            webServerMap.values().stream().findFirst().ifPresent(WebServer::start);
        }).start();
        logger.info("Chen Boot Start！！！");
        return chenApplicationContext;
    }

    /**
     * 打印banner
     */
    private static void printBanner(Logger logger) {
        URL resource = ChenApplication.class.getClassLoader().getResource("banner.txt");
        if (resource != null) {
            File file = new File(resource.getFile());
            if (file.exists()) {
                FileReader fileReader = null;
                try {
                    char[] bytes = new char[1024];
                    fileReader = new FileReader(file);
                    int read = fileReader.read(bytes);
                    String banner = new String(bytes, 0, read);
                    logger.info("\n" + banner);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (fileReader != null) {
                            fileReader.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
